//
//  ZBRichScrollView.m
//  XZBProduct
//
//  Created by xzb on 2018/8/8.
//  Copyright © 2018年 xzb. All rights reserved.
//

#import "ZBRichScrollView.h"
#import <KVOController/KVOController.h>

@interface ZBRichScrollView ()

@property (nonatomic, strong) NSArray<NSValue *> *oriFrameArray;

@end

@implementation ZBRichScrollView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        __weak typeof(self) weakSelf = self;
        [self.KVOController observe:self keyPath:@"contentOffset" options:NSKeyValueObservingOptionNew block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf handleTargetView];
        }];
    }
    return self;
}

- (void)setTargetViews:(NSArray *)targetViews
{
    _targetViews = targetViews;
    NSMutableArray *oriFrameArray = [[NSMutableArray alloc] init];
    for (UIView *subView in targetViews) {
        [oriFrameArray addObject:[NSValue valueWithCGRect:subView.frame]];
    }
    self.oriFrameArray = oriFrameArray;
}

- (void)handleTargetView
{
    if (self.targetViews.count < 1) {
        return;
    }
    CGFloat offsetY = self.contentOffset.y;
    UIView *selectedView = nil;
    NSUInteger idx = 0;
    for (UIView *targetView in self.targetViews) {
        targetView.frame = [self.oriFrameArray[idx] CGRectValue];
        if (!selectedView) {
            CGRect tmpRect = targetView.frame;
            if (CGRectGetMinY(tmpRect) < offsetY) {
                //需要悬停
                tmpRect.origin.y = offsetY;
                targetView.frame = tmpRect;
                selectedView = targetView;
            }
        } else {
            if (CGRectGetMinY(targetView.frame) < CGRectGetMaxY(selectedView.frame)) {
                //准备悬停,让当前悬停的frameMaxY = 下一个的minY;
                CGRect tmpRect = selectedView.frame;
                tmpRect.origin.y = CGRectGetMinY(targetView.frame) - CGRectGetHeight(selectedView.frame);
                selectedView.frame = tmpRect;
            }
            if (CGRectGetMinY(targetView.frame) <= offsetY) {
                //需要悬停
                CGRect headerRect = targetView.frame;
                headerRect.origin.y = offsetY;
                targetView.frame = headerRect;
                selectedView = targetView;
            }
        }
        [self bringSubviewToFront:targetView];
        idx++;
    }
}

@end
